package com.tyf.common.web.config;


import com.tyf.common.web.feign.EudFeignResultVoDecoder;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.WeightedResponseTimeRule;
import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
@ConfigurationProperties("feign")
public class FeignConfiguration {
	private Logger.Level loggerLevel;

	//@Bean
	//TODO 不要声明为 @Bean，该负载均衡机制会导致应用程序启动后，过一段时间服务调用会报404错误，先屏蔽此配置，原因待查
	public IRule ribbonRule(){
		return new WeightedResponseTimeRule();
	}
	
	/**
	 * 配置解码器
	 * @return
	 */
	@Bean
	public Decoder feignDecoder() {
		return new EudFeignResultVoDecoder();
	}
	
	/**
	 * api接口认证， 主要给api接口增加Token，用于各应同步用户信息
	 * @return
	 */

	// TODO: api工程若未禁用hystrix，则会启动报错. 等后续使用hystix时，再考虑注释
	@Bean
	@Primary
	public Feign.Builder feignBuilder() {
		Feign.Builder builder = Feign.builder();
		//调整链接超时的时间 连接超时10秒 ， 读取超时120秒
		Request.Options ops = new Request.Options(10*1000,120*1000);
		builder.options(ops);

		return builder;
	}

	/**
	 * 日志级别可配置
	 * @return
	 */
	@Bean
	Logger.Level feignLoggerLevel() {
		return (loggerLevel==null ? Logger.Level.NONE:loggerLevel);
	}

	public Logger.Level getLoggerLevel() {
		return loggerLevel;
	}

	public void setLoggerLevel(Logger.Level loggerLevel) {
		this.loggerLevel = loggerLevel;
	}
}
